<?php
/**
 * CSearchPortlet class file.
 *
 * @author Lucas Vasconcelos <contato@lucasvasconcelos.com>
 * @copyright Copyright(c) 2010 Lucas Vasconcelos
 * @license BSD License http://www.lucasvasconcelos.com/yap/license
 * @link http://www.lucasvasconcelos.com/yap/
 * @version $Id: CSearchPortlet.php 18 2010-02-05 20:23:58Z contato@lucasvasconcelos.com $
 * @package yap.web.portlets
 */

Prado::using('yap.web.portlets.CPortlet');

/**
 * CSearchPortlet class.
 *
 * Add search capability to CPageGrid childs.
 * Just put at your template and it works!
 *
 * <code>
 * <com:yap.web.portlets.CSearchPortlet />
 * </code>
 *
 * Remember to put :search_keyword special token at your
 * CriteriaCondition property.
 *
 * @author Lucas Vasconcelos <contato@lucasvasconcelos.com>
 * @version 1.0 $Revision: 18 $
 * @package yap.web.portlets
 */
class CSearchPortlet extends CPortlet
{
	public function getRequiredParent()
	{
		return 'CPageGrid';
	}

	/**
	 * Attach a new event handler to {@link CPageGrid::onSetupCriteria OnSetupCriteria} event.
	 * @see yap/web/portlets/CPortlet#onInit($param)
	 */
	public function onInit($param)
	{
		parent::onInit($param);
		$this->getPage()->attachEventHandler('OnSetupCriteria',array($this,'setupCriteria'));
	}

	/**
	 * Handler to OnSetupCriteria event.
	 * If has defined :search_keyword parameter then binds the user input to the
	 * criteria parameter.
	 */
	public function setupCriteria($sender,$param)
	{
		Prado::trace('SearchPortlet setupCriteria()','yap.web.portlets');
		$criteria=$sender->getGridManager()->getCriteria();
		if(preg_match('/:\bsearch_keyword\b/',$sender->getCriteriaCondition())>0)
		{
			$criteria->setCondition($sender->getCriteriaCondition());
			$criteria->Parameters[':search_keyword']=$this->search_keyword->getText().'%';
			$sender->getGridManager()->setCriteria($criteria);
		}
	}

	/**
	 * Handler to search button OnClick event.
	 */
	public function search($sender,$param)
	{
		$this->processRequest();
	}

	/**
	 * Handler to clear button OnClick event.
	 */
	public function clear($sender,$param)
	{
		Prado::trace('CSearchPortlet clearCriteria()','yap.web.portlets');
		$this->getPage()->getGridManager()->clearCriteria();
		$this->search_keyword->setText('');
		$this->processRequest();
	}

	/**
	 * Call the appropriate methods to do the search.
	 */
	protected function processRequest()
	{
		Prado::trace('CSearchPortlet onSetupCriteria()','yap.web.portlets');
		$this->getPage()->onSetupCriteria(null);

		Prado::trace('CSearchPortlet onLoadGrid()','yap.web.portlets');
		$this->getPage()->onLoadGrid(null);
	}
}